﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;

namespace JasLib.Interop.Win32
{
    public static partial class SECUR32
    {
        [DllImport(Constants.ModuleNames.SECUR32, EntryPoint = "GetUserNameExW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        public static extern BOOLEAN GetUserNameEx(
            [In] EXTENDED_NAME_FORMAT NameFormat,
            [Out] StringBuilder lpNameBuffer,
            [In, Out] ref uint lpnSize);

        /// <summary>
        /// Convenient wrapper for the GetUserNameEx Win32 function that throws an exception on failure.
        /// </summary>
        public static string GetUserNameEx(EXTENDED_NAME_FORMAT NameFormat)
        {
            StringBuilder buffer = new StringBuilder(0);
            uint uiLength = 0;
            GetUserNameEx(NameFormat, buffer, ref uiLength);
            var error = KERNEL32.GetLastError();
            if (error != Win32ErrorCode.ERROR_MORE_DATA)
                error.TryThrowWin32Exception();

            buffer.Capacity = (int)uiLength;
            if (GetUserNameEx(NameFormat, buffer, ref uiLength) != BOOLEAN.TRUE)
                KERNEL32.GetLastError().TryThrowWin32Exception();

            return buffer.ToString();
        }
    }
}
